package com.javacoo.swing.jxbrowser.content;

import java.awt.BorderLayout;
import java.nio.charset.Charset;
import java.util.logging.Level;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.javacoo.swing.jxbrowser.BaseBrowser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.DataReceivedParams;
import com.teamdev.jxbrowser.chromium.LoggerProvider;
import com.teamdev.jxbrowser.chromium.NetworkService;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;

/**
 * 访问HTTP响应数据
 * <li></li>
 * JxBrowser API提供了允许访问HTTP响应数据的功能，例如HTML，纯文本，JavaScript代码，CSS，图像等。使用此功能，您可以使用有关其mime类型的信息捕获AJAX响应正文内容。以下示例演示了如何使用此功能访问每个响应的text / html数据
 * @author: duanyong@jccfc.com
 * @since: 2020/9/27 9:01
 */
public class AccessingHttpResponseData extends BaseBrowser {
    public static void main(final String[] args) {
        LoggerProvider.setLevel(Level.OFF);

        BrowserContext browserContext = BrowserContext.defaultContext();
        NetworkService networkService = browserContext.getNetworkService();
        networkService.setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public void onDataReceived(DataReceivedParams params) {
                if (params.getMimeType().equals("text/html")) {
                    String data = new String(params.getData(),
                        Charset.forName("UTF-8"));
                    System.out.println("data = " + data);
                }
            }
        });

        Browser browser = new Browser(browserContext);
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.loadURL(BASE_URL);
    }
}
